//多线程聊天程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>

void *receive_message(void *arg) 
{
    int client_socket = *(int *)arg;
    while (1)
     {
        char message[1024];
        memset(message, 0, sizeof(message));
        if (recv(client_socket, message, sizeof(message), 0) <= 0) 
        {
            close(client_socket);
            break;
        }
        printf("%s\n", message);
    }
    return NULL;
}

void *send_message(void *arg) 
{
    int client_socket = *(int *)arg;
    while (1) 
    {
        char message[1024];
        memset(message, 0, sizeof(message));
        fgets(message, sizeof(message), stdin);
        if (send(client_socket, message, strlen(message), 0) <= 0) 
        {
            close(client_socket);
            break;
        }
    }
    return NULL;
}

int main()
 {
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1)
     {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(8000);
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) 
    {
        perror("bind");
        exit(EXIT_FAILURE);
    }
    if (listen(server_socket, 5) == -1)
     {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    printf("Server is listening...\n");
    while (1)
     {
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_socket == -1)
         {
            perror("accept");
            exit(EXIT_FAILURE);
        }
        printf("Connected with %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
        pthread_t receive_thread;
        pthread_create(&receive_thread, NULL, receive_message, &client_socket);
        pthread_detach(receive_thread);
        pthread_t send_thread;
        pthread_create(&send_thread, NULL, send_message, &client_socket);
        pthread_detach(send_thread);
    }
    close(server_socket);
    return 0;
}
